import { ref } from 'vue'
import type { OrderType, OrderListParams, OrderItem } from '@/types/order'
import {
  getOrderListApi,
  cancelConsultApi,
  deleteConsultApi
} from '@/services/order'
import { showConfirmDialog, showFailToast, showToast } from 'vant'

export function consult() {
  const loading = ref(false)
  const finished = ref(false)

  const queryConsult = ref<OrderListParams>({
    current: 1,
    pageSize: 10,
    type: 1
  })

  const pageTotal = ref(0)
  const consultList = ref<OrderItem[]>([])

  const getConsultList = async (type: OrderType, isFirst: boolean = false) => {
    if (!type) return
    queryConsult.value.type = type
    if (isFirst) {
      consultList.value = []
      finished.value = false
      queryConsult.value.current = 1
    }
    try {
      const { data } = await getOrderListApi(queryConsult.value)
      pageTotal.value = data.pageTotal
      consultList.value = consultList.value.concat(data.rows)
      if (pageTotal.value <= queryConsult.value.current) {
        finished.value = true
      } else {
        queryConsult.value.current += 1
      }
    } catch (error) {
      showToast('获取失败')
    } finally {
      loading.value = false
    }
  }

  const cancelLoading = ref(false)
  const cancelConsult = (id: string, item: OrderItem) => {
    showConfirmDialog({
      title: '温馨提醒',
      message: '是否确认取消订单'
    }).then(async () => {
      try {
        cancelLoading.value = true
        await cancelConsultApi(id)
        item.status = 5
        item.statusValue = '已取消'
      } catch (error) {
        showFailToast('取消失败')
      } finally {
        cancelLoading.value = false
      }
    })
  }

  const deleteLoading = ref(false)
  const deleteConsult = (id: string, type: OrderType) => {
    showConfirmDialog({
      title: '温馨提醒',
      message: '是否确认删除订单'
    }).then(async () => {
      try {
        deleteLoading.value = true
        await deleteConsultApi(id)
        getConsultList(type, true)
      } catch (error) {
        showFailToast('删除失败')
      } finally {
        deleteLoading.value = false
      }
    })
  }

  const onLoad = (type: OrderType) => {
    getConsultList(type)
  }

  return {
    loading,
    finished,
    consultList,
    onLoad,
    cancelLoading,
    cancelConsult,
    deleteLoading,
    deleteConsult
  }
}
